import axios from 'axios'

const env = require('./env').dev

let instance = axios.create()

instance.headers = {
  'content-type': 'application/json'
}

instance.baseUrl = env.baseUrl

// http request 拦截器
instance.interceptors.request.use(
  config => {
    console.log("请求拦截器")
    // const token = sessionStorage.getItem('token')
    // if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
      // config.headers.authorization = token  //请求头加上token
      config.headers.authorization = 111111
    // }
    console.log(config)
    return config
  },
  err => {
    console.log("请求拦截器错误")
    return Promise.reject(err)
  })

// http response 拦截器
instance.interceptors.response.use(
  response => {
    //拦截响应，做统一处理 
    console.log("响应拦截器")
    return response
  },
  //接口错误状态处理，也就是说无响应时的处理
  error => {
    console.log("响应拦截器错误")
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  })

//解决微信小程序直接使用 axios 会报错的问题
instance.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    // wx小程序 发起相应请求
    console.log("执行自定义方法")
    console.log(instance.baseUrl)
    console.log(config.headers)
    wx.request({
      url: instance.baseUrl + config.url,
      method: config.method,
      data: data,
      header: config.headers,
      success:(res)=>{return resolve(res)},
      fail:(err)=>{return reject(err)}
    })
  })
}

//封装 axios 请求函数
function request(url, params={}, method='GET'){
  return instance({
    method,
    url,
    params
  })
}

function GET(url, params={}){
  return request(url, params, 'GET')
}
    
function POST(url, params={}){
  return request(url, params, 'POST')
}

function PUT(url, params={}){
  return request(url, params, 'PUT')
}
    
function PATCH(url, params={}){
  return request(url, params, 'PATCH')
}
    
function DELETE(url, params={}){
  return request(url, params, 'DELETE')
}

function CONNECT(url, params={}){
  return request(url, params, 'CONNECT')
}

function OPTIONS(url, params={}){
  return request(url, params, 'OPTIONS')
}
    
function HEAD(url, params={}){
  return request(url, params, 'HEAD')
}

function TRACE(url, params={}){
  return request(url, params, 'TRACE')
}

export default {
    Request: request,
    GET: GET,
    POST: POST,
    PUT: PUT,
    PATCH: PATCH,
    DELETE: DELETE,
    CONNECT: CONNECT,
    OPTIONS: OPTIONS,
    HEAD: HEAD,
    TRACE: TRACE,
}